﻿using System.Linq;
using FPP.Models;
using FPP.Controllers;
using System.Xml;
using System.ServiceModel.Syndication;


namespace FPP.Utilities
{
    public class NewsFeeds
    {
        public static void CheckNewsFeeds()
        {
            var model = new DeadCelebBlog();
            const string strFeed = "http://feeds.feedburner.com/deadceleb";
            using (XmlReader reader = XmlReader.Create(strFeed))
            {
                SyndicationFeed rssData = SyndicationFeed.Load(reader);
                model.DeadBlogFeed = rssData;
            }

            var context = new fppEntities(DataAccess.ffpCString);
            using (context)
            {
                if (model.DeadBlogFeed != null)
                    foreach (var item in model.DeadBlogFeed.Items)
                    {
                        SyndicationItem item1 = item;
                        var r = from n in context.News
                                where n.SourceUrl == item1.Id
                                select n.Id;

                        if (!r.Any())
                        {
                            var news = new News
                                           {
                                               SourceUrl = item.Id,
                                               Title = string.Format("{0}", item.Title.Text),
                                               Body =
                                                   string.Format("{0}. {1}", DcStripDoD(item.Summary.Text),
                                                                 "Read more at http://dead-celeb.com"),
                                               DateOfNews = item.PublishDate.Date,
                                               Image = DcStripImage(item.Summary.Text)
                                           };

                            context.News.AddObject(news);

                        }
                    }

                context.SaveChanges();
            }
        }

        private static string DcStripImage(string p)
        {
            int titleStart = p.IndexOf("src=", System.StringComparison.Ordinal);
            int titleEnd = p.IndexOf(" border", System.StringComparison.Ordinal);
            titleStart = titleStart + 4;

            return p.Substring(titleStart, titleEnd - titleStart).Replace("\"","");
        }

        private static string DcStripDoD(string body)
        {
            int titleStart = body.IndexOf("<p>Died", System.StringComparison.Ordinal);
            int titleEnd = body.IndexOf(".</p>", System.StringComparison.Ordinal);
            titleStart = titleStart + 3;

            return body.Substring(titleStart , titleEnd - titleStart);

        }
    }
}